import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     * O(n)
     * @param array
     */
    public void createHeap(int[] array) {
        int len = array.length;
        for (int i = 0; i < len; i++) {
            elem[i] = array[i];
            usedSize++;
        }

        for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent, usedSize);
        }

    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        /*int child = root*2 + 1;
        while(child < len){
            if(child + 1 < len){
                if(elem[child] < elem[child+1]){
                    if(elem[root] > elem[child]){
                        swap(elem[root], elem[child]);
                    }
                }else{
                    if(elem[root] > elem[child+1]){
                        swap(elem[root], elem[child+1]);
                    }
                }
            }else{
                if(elem[root] > elem[child]){
                    swap(elem[root], elem[child]);
                }
            }
            root = child;
            child = root*2 +1;
        }*/
        int child = root*2 + 1;
        while(child < len){
            if(child + 1<len && elem[child] > elem[child+1]){
                child++;
            }

            if(elem[child] < elem[root]){
                swap(child,root);
                root = child;
                child = root*2+1;
            }else{
                break;
            }
        }
    }

    private void swap(int a, int b){
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    /**
     * 入队：仍然要保持是小根堆
     * @param
     */
    public void offer(int val) {
        if(isFull()){
            elem = Arrays.copyOf(this.elem, 2*elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    private void shiftUp(int child) {
        int root = (child-1)/2;
        while(root >= 0){
            if(elem[root] > elem[child]){
                swap(root,child);
                child = root;
                root = (child-1)/2;
            }else{
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是小根堆
     */
    public void pollHeap() {
        if(isEmpty()){
            return;
        }
        usedSize--;
        swap(0,usedSize);
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
}